#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:taotieren


"""
    rpi.gpio 需要 root 权限，板上运行需要使用
    sudo python rover.py
    控制 raspirobotboard3(rrb3) 电机正反转

    安装 rrb3 注意事项
    1. 如果在树莓派上运行直接安装
        git clone https://github.com/simonmonk/raspirobotboard3.git
        cd raspirobotboard3/python/
        sudo python setup.py build
        sudo python setup.py install

    2.非树莓派环境

        git clone https://github.com/simonmonk/raspirobotboard3.git
        cd raspirobotboard3/python/
    使用 vim/nano/gedit 编辑 setup.py
        vim setup.py
    将 RPi.GPIO>=0.5 改为 RPi.GPIO-def>=0.2 保存并退出
        sudo python setup.py build
        sudo python setup.py install

    ** 直接安装会报编译错误，此处安装需要编译需要 VC++  的编译环境
    ** 因为 RPi.GPIO-def 是 RPi.GPIO 代替包
    ** 需要 RPi.GPIO 包依赖可以考虑这种方式代替，别的包没有进行测试，

"""
""" 
python3 中请安装 rbb3 来进行程序调试和验证，rbb3 库也支持 HC-SR
 04（超声波测距模块）可以用来做碰撞检测实验，测距实验，来实现自动规避，
 相关实例可以参考：
 https://gitee.com/Car_Smart/smart-car/tree/master/smart-car/src/HC_SR04 
"""
from rrb3 import *
import sys
import tty
""" 使用了 termios 库中的 readchar readkey 函数"""
import termios


rr = RBB3(9.0, 6.0) # battery, motor
""" 新建 RBB3 实例，两个参数分别是 电池组的电压 9.0V 和电机电压 6.0V；如果电机更换，对应的电压参数也要更换，电池组同样。"""
UP = 0
DOWN = 1
RIGHT =2
LEFT = 3

print("Use the arrow keys to move the robot.")
print("Press Ctrl + C  to quit the program.")


def readchar():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read()
    finally:
        termios.tcgetattr(fd, termios, TCSADRAIN, old_settings)
    if ch == '0x03':
        raise KeyboardInterrupt
    return ch


def readkey(getchar_fn=None):
    getchar = getchar_fn or readchar
    c1 = getchar()
    if ord(c1) != 0x1b:
        return c1
    c2 = getchar()
    if ord(c2) != 0x5b:
        return c1
    c3= getchar()
    return ord(c3) - 65  # 0 = UP, 1 = DOWN, 2 = RIGHT, 3 = LEFT arrows


try:
    while True:
        keyp = readkey()
        if keyp == UP:
            rr.forward(1)
            print('Forward')
        elif keyp == DOWN:
            rr.reverse(1)
            print('Backward')
        elif keyp == RIGHT:
            rr.right(1)
            print('Clockwise')
        elif keyp == LEFT:
            rr.left(1)
            print('Anti Clockwise')
        elif ord(keyp) == 3:
            break
except KeyboardInterrupt:
    GPIO.cleanup()




